<template>
  <div class="settings-page">
    <div class="page-header">
      <h2>账号设置</h2>
      <p class="page-description">管理您的账户信息和安全设置</p>
    </div>

    <el-tabs v-model="activeTab" type="border-card" class="settings-tabs">
      <!-- 基本资料标签页 -->
      <el-tab-pane label="基本资料" name="profile">
        <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            class="profile-form"
        >
          <!-- 头像上传区域 -->
          <el-form-item label="头像" prop="avatar">
            <div class="avatar-upload-section">
              <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :http-request="customAvatarUpload"
                  :before-upload="beforeAvatarUpload"
                  :on-success="handleAvatarSuccess"
                  :on-error="handleAvatarError"
                  accept="image/jpeg,image/png,image/gif"
              >
                <el-avatar v-if="profileForm.avatar" :size="100" :src="profileForm.avatar" class="avatar" />
                <div v-else class="avatar-uploader-trigger">
                  <el-icon><Plus /></el-icon>
                  <span>上传头像</span>
                </div>
                <template #tip>
                  <div class="el-upload__tip">支持 jpg、png、gif 格式，大小不超过 2MB</div>
                </template>
              </el-upload>
              <div class="avatar-tips">
                <p>建议尺寸：100×100像素</p>
                <p>支持 JPG、PNG 格式，大小不超过 2MB</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="profileForm.username"
                placeholder="请输入用户名"
                maxlength="20"
                show-word-limit
            />
          </el-form-item>

          <el-form-item label="个人简介" prop="description">
            <el-input
                v-model="profileForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入个人简介"
                maxlength="100"
                show-word-limit
            />
          </el-form-item>

          <el-form-item label="邮箱地址" prop="email">
            <el-input
                v-model="profileForm.email"
                placeholder="请输入邮箱地址"
            />
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profileForm.gender">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
              <el-radio label="secret">保密</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="生日" prop="birthday">
            <el-date-picker
                v-model="profileForm.birthday"
                type="date"
                placeholder="选择生日"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="所在地" prop="location">
            <el-cascader
                v-model="profileForm.location"
                :options="locationOptions"
                placeholder="请选择所在地"
            />
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                @click="handleProfileSubmit"
                :loading="profileLoading"
            >
              保存资料
            </el-button>
            <el-button @click="resetProfileForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 安全设置标签页 -->
      <el-tab-pane label="安全设置" name="security">
        <div class="security-settings">
          <!-- 密码修改 -->
          <el-card class="security-card">
            <div class="card-header">
              <h3>修改密码</h3>
              <el-button
                  type="primary"
                  size="small"
                  @click="showPasswordDialog = true"
              >
                修改密码
              </el-button>
            </div>
            <p class="card-description">定期修改密码可以提高账户安全性</p>
          </el-card>

          <!-- 手机绑定 -->
          <el-card class="security-card">
            <div class="card-header">
              <h3>手机绑定</h3>
              <el-button
                  v-if="userInfo.phone"
                  type="warning"
                  size="small"
                  @click="showPhoneDialog = true"
              >
                更换手机
              </el-button>
              <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="showPhoneDialog = true"
              >
                绑定手机
              </el-button>
            </div>
            <p class="card-description">
              {{ userInfo.phone ? `已绑定手机：${userInfo.phone}` : '尚未绑定手机' }}
            </p>
          </el-card>

          <!-- 邮箱绑定 -->
          <el-card class="security-card">
            <div class="card-header">
              <h3>邮箱绑定</h3>
              <el-button
                  v-if="userInfo.email"
                  type="warning"
                  size="small"
                  @click="showEmailDialog = true"
              >
                更换邮箱
              </el-button>
              <el-button
                  v-else
                  type="primary"
                  size="small"
                  @click="showEmailDialog = true"
              >
                绑定邮箱
              </el-button>
            </div>
            <p class="card-description">
              {{ userInfo.email ? `已绑定邮箱：${userInfo.email}` : '尚未绑定邮箱' }}
            </p>
          </el-card>

          <!-- 登录设备管理 -->
          <el-card class="security-card">
            <div class="card-header">
              <h3>登录设备管理</h3>
              <el-button type="info" size="small" @click="viewLoginDevices">
                查看设备
              </el-button>
            </div>
            <p class="card-description">管理您已登录的设备，可远程退出不常用设备</p>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 隐私设置标签页 -->
      <el-tab-pane label="隐私设置" name="privacy">
        <el-form label-width="150px" class="privacy-form">
          <el-form-item label="谁可以看我的动态">
            <el-radio-group v-model="privacySettings.dynamicVisibility">
              <el-radio label="public">所有人</el-radio>
              <el-radio label="friends">仅好友</el-radio>
              <el-radio label="private">仅自己</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="谁可以给我发私信">
            <el-radio-group v-model="privacySettings.messagePermission">
              <el-radio label="all">所有人</el-radio>
              <el-radio label="mutual">互相关注</el-radio>
              <el-radio label="none">不允许</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="推荐可能认识的人">
            <el-switch v-model="privacySettings.recommendFriends" />
          </el-form-item>

          <el-form-item label="个性化内容推荐">
            <el-switch v-model="privacySettings.personalizedRecommend" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="savePrivacySettings">
              保存隐私设置
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 修改密码对话框 -->
    <el-dialog
        v-model="showPasswordDialog"
        title="修改密码"
        width="500px"
        @close="resetPasswordForm"
    >
      <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
              v-model="passwordForm.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button
            type="primary"
            @click="handlePasswordChange"
            :loading="passwordLoading"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 绑定手机对话框 -->
    <el-dialog
        v-model="showPhoneDialog"
        :title="userInfo.phone ? '更换手机号' : '绑定手机号'"
        width="500px"
    >
      <el-form :model="phoneForm" :rules="phoneRules" label-width="100px">
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="phoneForm.phone"
              placeholder="请输入手机号"
              maxlength="11"
          />
        </el-form-item>

        <el-form-item label="验证码" prop="smsCode">
          <div class="sms-code-input">
            <el-input
                v-model="phoneForm.smsCode"
                placeholder="请输入验证码"
                maxlength="6"
            />
            <el-button
                :disabled="smsCountdown > 0"
                @click="sendSmsCode"
                class="sms-btn"
            >
              {{ smsCountdown > 0 ? `${smsCountdown}s后重试` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showPhoneDialog = false">取消</el-button>
        <el-button
            type="primary"
            @click="handlePhoneBind"
            :loading="phoneLoading"
        >
          {{ userInfo.phone ? '更换手机' : '绑定手机' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import Cookies from 'js-cookie'
import { Plus } from '@element-plus/icons-vue'
import {
  getUserFromLocalStorage,
  updateUserInLocalStorage
} from '@/utils/localStorageUser'

// API配置
const RAW_API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:80'
const API_BASE_URL = RAW_API_BASE_URL.replace(/:8080\b/, ':80')

// 创建统一的Axios实例，全局配置withCredentials
const api = axios.create({
  baseURL: API_BASE_URL,
  withCredentials: true, // 全局允许携带Cookie[1,3](@ref)
  timeout: 10000
})

// 请求拦截器：自动添加认证令牌
api.interceptors.request.use(
    (config) => {
      const token = getAuthToken()
      if (token) {
        // 确保satoken写入Cookie，方便后端基于Cookie认证
        Cookies.set('satoken', token, { path: '/', expires: 7 })
        // 同时设置Authorization头，双重保障
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
)

// 响应拦截器：统一处理认证失败
api.interceptors.response.use(
    (response) => {
      return response
    },
    (error) => {
      if (error.response?.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        // 可以在这里跳转到登录页
      }
      return Promise.reject(error)
    }
)

// 响应式数据
const activeTab = ref('profile')
const profileLoading = ref(false)
const passwordLoading = ref(false)
const phoneLoading = ref(false)
const smsCountdown = ref(0)

// 对话框控制
const showPasswordDialog = ref(false)
const showPhoneDialog = ref(false)
const showEmailDialog = ref(false)

// 表单引用
const profileFormRef = ref(null)
const passwordFormRef = ref(null)

// 用户信息
const userInfo = ref({
  username: '用户',
  description: '这个人很懒，什么都没有写',
  email: '',
  phone: '',
  sex: 'secret',
  birthday: '',
  location: [],
  avatar: ''
})

// 表单数据
const profileForm = reactive({ ...userInfo.value })

// 获取认证令牌的函数
const getAuthToken = () => {
  return localStorage.getItem('token') || ''
}

// 从localStorage加载用户信息
const loadUserInfo = () => {
  try {
    const userData = getUserFromLocalStorage()
    if (userData) {
      // 更新用户信息
      userInfo.value = {
        username: userData.username || '用户',
        description: userData.description || '这个人很懒，什么都没有写',
        email: userData.email || '',
        phone: userData.phone || '',
        sex: userData.sex || 'secret',
        birthday: userData.birthday || '',
        location: userData.location || [],
        avatar: userData.avatar || ''
      }

      // 更新表单数据
      Object.assign(profileForm, userInfo.value)
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const phoneForm = reactive({
  phone: '',
  smsCode: ''
})

const privacySettings = reactive({
  dynamicVisibility: 'public',
  messagePermission: 'mutual',
  recommendFriends: true,
  personalizedRecommend: true
})

// 表单验证规则
const profileRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
      message: '用户名只能包含中文、英文、数字和下划线',
      trigger: 'blur'
    }
  ],
  description: [
    { max: 100, message: '个人简介不能超过100个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).{6,}$/,
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 地区选择选项
const locationOptions = [
  {
    value: 'beijing',
    label: '北京市',
    children: [
      { value: 'dongcheng', label: '东城区' },
      { value: 'xicheng', label: '西城区' }
    ]
  },
  {
    value: 'shanghai',
    label: '上海市',
    children: [
      { value: 'huangpu', label: '黄浦区' },
      { value: 'xuhui', label: '徐汇区' }
    ]
  }
]

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG、PNG 或 GIF 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义头像上传方法
const customAvatarUpload = async (options) => {
  const { file, onSuccess, onError, onProgress } = options

  try {
    // 创建FormData，确保字段名为"avatar"
    const formData = new FormData()
    formData.append('avatar', file)  // 关键：字段名必须为avatar[8](@ref)

    const token = getAuthToken()
    if (!token) {
      ElMessage.error('未检测到登录信息，请重新登录')
      onError(new Error('未登录'))
      return
    }

    // 配置请求
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total > 0) {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          onProgress({ percent })
        }
      }
    }

    // 使用统一的api实例发送上传请求，自动携带Cookie和token
    const response = await api.post('/user/avatar', formData, config)

    if (response.status === 200 && response.data.code === 0) {
      onSuccess(response.data)
    } else {
      const errorMsg = response.data?.message || '上传失败'
      onError(new Error(errorMsg))
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    onError(error)
    ElMessage.error(error.response?.data?.message || '头像上传失败，请重试')
  }
}

const handleAvatarSuccess = (response) => {
  if (response && response.code === 0) {
    const avatarUrl = response.data?.url || response.data?.avatarUrl || response.url
    if (avatarUrl) {
      profileForm.avatar = avatarUrl
      userInfo.value.avatar = avatarUrl

      // 更新本地存储
      const userData = getUserFromLocalStorage()
      if (userData) {
        userData.avatar = avatarUrl
        localStorage.setItem('userInfo', JSON.stringify(userData))
      }

      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error('头像上传成功，但未获取到有效URL')
    }
  } else {
    ElMessage.error(response?.message || '头像上传失败')
  }
}

const handleAvatarError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请重试')
}

// 个人资料保存
const handleProfileSubmit = async () => {
  if (!profileFormRef.value) return

  try {
    const valid = await profileFormRef.value.validate()
    if (valid) {
      profileLoading.value = true

      const token = getAuthToken()
      if (!token) {
        ElMessage.error('未检测到登录信息，请重新登录')
        return
      }

      // 使用统一的api实例发送请求，自动携带Cookie和token
      const response = await api.post('/user/update', profileForm)

      if (response.status === 200 && response.data.code === 0) {
        ElMessage.success('资料保存成功')

        // 更新用户信息
        Object.assign(userInfo.value, profileForm)

        // 保存到 localStorage
        const updatedUser = updateUserInLocalStorage(profileForm)
        if (updatedUser) {
          // 触发全局用户信息更新事件
          window.dispatchEvent(new CustomEvent('userInfoUpdated', {
            detail: updatedUser
          }))
        }
      } else {
        ElMessage.error(response.data.message || '资料保存失败')
      }
    }
  } catch (error) {
    console.error('资料保存失败:', error)
    ElMessage.error(error.response?.data?.message || '网络错误，请重试')
  } finally {
    profileLoading.value = false
  }
}

const resetProfileForm = () => {
  Object.assign(profileForm, userInfo.value)
  ElMessage.info('表单已重置')
}

// 密码修改
const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return

  try {
    const valid = await passwordFormRef.value.validate()
    if (valid) {
      passwordLoading.value = true

      // 使用统一的api实例
      const response = await api.post('/user/password', {
        oldPassword: passwordForm.currentPassword,
        newPassword: passwordForm.newPassword
      })

      if (response.status === 200 && response.data.code === 0) {
        ElMessage.success('密码修改成功')
        showPasswordDialog.value = false
        resetPasswordForm()
      } else {
        ElMessage.error(response.data.message || '密码修改失败')
      }
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error(error.response?.data?.message || '网络错误，请重试')
  } finally {
    passwordLoading.value = false
  }
}

const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

// 手机绑定相关
const sendSmsCode = async () => {
  if (!phoneForm.phone) {
    ElMessage.warning('请输入手机号')
    return
  }

  const token = getAuthToken()
  if (!token) {
    ElMessage.error('未检测到登录信息，请重新登录')
    return
  }

  try {
    // 使用统一的api实例
    await api.post('/user/code', { phoneNum: phoneForm.phone })

    // 启动倒计时
    smsCountdown.value = 60
    const timer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    ElMessage.success('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  }
}

const handlePhoneBind = async () => {
  phoneLoading.value = true

  const token = getAuthToken()
  if (!token) {
    ElMessage.error('未检测到登录信息，请重新登录')
    return
  }

  try {
    // 使用统一的api实例
    const response = await api.post('/user/phone', {
      phoneNum: phoneForm.phone,
      smsCode: phoneForm.smsCode
    })

    if (response.status === 200 && response.data.code === 0) {
      userInfo.value.phone = phoneForm.phone
      ElMessage.success(userInfo.value.phone ? '手机号更换成功' : '手机号绑定成功')
      showPhoneDialog.value = false

      // 更新本地存储的用户信息
      const userData = getUserFromLocalStorage()
      if (userData) {
        userData.phone = phoneForm.phone
        localStorage.setItem('userInfo', JSON.stringify(userData))
      }
    } else {
      ElMessage.error(response.data.message || '手机绑定失败')
    }
  } catch (error) {
    console.error('手机绑定失败:', error)
    ElMessage.error(error.response?.data?.message || '网络错误，请重试')
  } finally {
    phoneLoading.value = false
  }
}

// 隐私设置
const savePrivacySettings = async () => {
  const token = getAuthToken()
  if (!token) {
    ElMessage.error('未检测到登录信息，请重新登录')
    return
  }

  try {
    // 使用统一的api实例
    const response = await api.post('/user/privacy', privacySettings)

    if (response.status === 200 && response.data.code === 0) {
      ElMessage.success('隐私设置保存成功')
    } else {
      ElMessage.error(response.data.message || '隐私设置保存失败')
    }
  } catch (error) {
    console.error('隐私设置保存失败:', error)
    ElMessage.error(error.response?.data?.message || '网络错误，请重试')
  }
}

const viewLoginDevices = () => {
  ElMessage.info('跳转到登录设备管理页面')
}

// 生命周期
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.settings-page {
  padding: 30px;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 30px;
  text-align: left;
  padding-bottom: 20px;
  border-bottom: 1px solid #e7e7e7;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #18191c;
}

.page-description {
  margin: 0;
  color: #61666d;
  font-size: 14px;
}

.settings-tabs {
  margin-top: 0;
}

:deep(.settings-tabs .el-tabs__header) {
  margin-bottom: 0;
}

:deep(.settings-tabs .el-tabs__item) {
  font-size: 16px;
  padding: 0 24px;
  height: 50px;
  line-height: 50px;
}

:deep(.settings-tabs .el-tabs__item.is-active) {
  color: #00a1d6;
  font-weight: 600;
}

:deep(.settings-tabs .el-tabs__active-bar) {
  background-color: #00a1d6;
}

.profile-form,
.privacy-form {
  max-width: 700px;
  margin: 0 auto;
  padding: 30px;
}

:deep(.profile-form .el-form-item__label),
:deep(.privacy-form .el-form-item__label) {
  color: #18191c;
  font-weight: 500;
}

.security-settings {
  display: grid;
  gap: 16px;
  padding: 30px;
  max-width: 700px;
  margin: 0 auto;
}

.security-card {
  transition: all 0.3s ease;
}

.security-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  color: #18191c;
}

.card-description {
  margin: 0;
  color: #61666d;
  font-size: 14px;
}

.sms-code-input {
  display: flex;
  gap: 12px;
}

.sms-code-input .el-input {
  flex: 1;
}

.sms-btn {
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .settings-page {
    padding: 12px;
  }

  .profile-form,
  .privacy-form {
    padding: 12px;
  }

  .security-settings {
    padding: 12px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .sms-code-input {
    flex-direction: column;
  }
}
</style>